<template>
	<view class="container">
		<view class="header-wrap">
			<text class="title">活动列表</text>
			<view class="filter" @click="onOpenSearch()">
				<uni-icons type="settings" size="24"></uni-icons>
				<text>筛选</text>
			</view>
		</view>

		<view class="content-wrap">
			<view class="item" v-for="item in activityList">
				<view class="no">
					<text> 活动编号：</text>
					<text selectable="true" class="noN">{{ item.activityNo }}</text>
				</view>
				<view class="line"></view>
				<text class="title">{{ item.activityName }}{{ item.couponList?.length > 1 ? '（卡包）' : '' }}</text>
				<template v-if="item.couponList[0].isAllocation === 1">
					<view class="number">
						<text>本机构已分配：{{ couponAllocation(item.couponList) }}张</text>
						<text class="price">¥ {{ couponPrice(item.couponList) }}</text>
					</view>
					<view class="number">
						<text>本机构已派发：{{ couponConsume(item.couponList) }}张</text>
						<text>券面额</text>
					</view>
					<view class="number">
						<text>本机构剩余数量：{{ couponNum(item.couponList) }}张</text>
					</view>
					<!-- <view class="number" v-if="item.level ==2 || item.level ==3">
						<text>已分配下级机构：{{item.couponList[0].couponAssigned }}张</text>
						<text>券面额</text>
					</view> -->
				</template>
				<template v-else>
					<view class="number">
						<text>本机构已分配：{{ '--' }}</text>
						<text class="price">¥ {{ couponPrice(item.couponList) }}</text>
					</view>
					<view class="number">
						<text>本机构已派发：{{ '--' }}</text>
						<text>券面额</text>
					</view>
					<view class="number">
						<text>本卡券剩余数量：{{ couponRemain(item.couponList) }}张</text>
					</view>
				</template>

				<view class="number">
					<!-- <view class="qrcode">生成二维码</view> -->
					<view class="info" @click="onDetail(item.activityId,(couponNum(item.couponList)) || 0)">查看派券记录
					</view>

					<view class="history" @click="onScanCode(item.activityId,couponNum(item.couponList),item.couponList)">
						<uni-icons type="camera" color="white" size="26"></uni-icons>
						<text>扫码派券</text>
					</view>
				</view>
				<!-- 是否派发完毕标识 -->
				<image v-if="couponNum(item.couponList) <= 0" src="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/4226a699-118a-47c4-b909-0f5642fadec1.png"></image>
			</view>
			<gzListNull :list="activityList"></gzListNull>
		</view>

		<!-- 搜索弹窗 -->
		<uni-popup ref="searchPopup" type="top">
			<view class="popup-search">
				<view class="item">
					<text>活动编号</text>
					<input class="input" placeholder-style="color:#BBBBBB" placeholder="请输入活动编号"
						v-model="vdata.queryParams.activityNo" />
				</view>
				<view class="item">
					<text>活动名称</text>
					<input class="input" placeholder-style="color:#BBBBBB" placeholder="请输入活动名称"
						v-model="vdata.queryParams.activityName" />
				</view>
				<view class="item">
					<text>活动时间</text>
					<view class="time-wrap">
						<view class="time" @click="onOpenDate(true)">
							<text
								:style="vdata.queryParams.startTime?'':'color:#BBBBBB'">{{vdata.queryParams.startTime?vdata.queryParams.startTime:'开始时间'}}</text>
							<uni-icons type="down" color="#A0A9C0" size="20"></uni-icons>
						</view>
						<text class="to">至</text>
						<view :style="vdata.queryParams.endTime?'':'color:#BBBBBB'" class="time"
							@click="onOpenDate(false)">
							<text>{{vdata.queryParams.endTime?vdata.queryParams.endTime:'结束时间'}}</text>
							<uni-icons type="down" color="#A0A9C0" size="20"></uni-icons>
						</view>
					</view>
				</view>
				<view class="bottom-wrap">
					<text class="reset" @click="onReset">重置</text>
					<text class="query" @click="onQuery">查询</text>
				</view>
			</view>
		</uni-popup>

		<!-- 日历 -->
		<uni-calendar ref="calendarRef" :insert="false" @confirm="onConfirmDate" />
		<!-- 同主体派券 引导用户授权 二维码 -->
		<uni-popup ref="qrCodePopup" type="center" :safe-area="false">
			<view class="popup-container">
				<image :src="vdata.activityQrcodeImg"></image>
				<view>当前客户未授权，请客户扫码后，重新派券</view>
			</view>
		</uni-popup>
		<!-- 回执信息填写弹窗 -->
		<ReceiptInformation ref="receiptInformationRef" v-model:value="inputData" :receipt-type="vdata.scanCodeResult.receiptType" :receipt-content="vdata.scanCodeResult.receiptContent" @complete="complete"/>
	</view>
</template>

<script setup>
	import { reactive, ref, computed, getCurrentInstance } from 'vue'
	import { $sendToMchUserActivity, $sendToMchUser } from '@/http/marketing/apiMarketing.js'
	import storageManage from '@/util/storageManage.js'
	import { onShow, onLoad } from '@dcloudio/uni-app'
	import ReceiptInformation from '@/marketing/index/components/ReceiptInformation.vue'
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	// 搜索弹窗
	const searchPopup = ref();
	// 引导支付授权弹窗
	const qrCodePopup = ref()
	// 回执信息弹窗
	const receiptInformationRef = ref()

	// 搜索弹窗
	const calendarRef = ref();

	// 获取列表数据
	const activityList = ref([])

	onLoad(() => {
		refreshActivityList()
	})
	
	/**
	 * 刷新派券列表
	 */
	const refreshActivityList = async (params) => {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		const { bizData } = await $sendToMchUserActivity({ ...params,templateNo: 'ACTE006',agentNo: storageManage.userInfo().khjlAgentNo })
		uni.hideLoading()
		activityList.value = bizData
	}

	const vdata = reactive({
		queryParams: {
			activityNo: '',
			activityName: '',
			startTime: '',
			endTime: ''
		},
		isStartDate: true,
		activityQrcodeImg: '',	// 扫码派券失败 引导用户授权图片
		
		isOpenReceipt: 0, // 是否需要回执信息
		scanCodeResult: {}, // 扫码结果
	})
	// 回执信息
	const inputData = ref()
	// 未限制卡券分配数量的卡券余量
	const couponRemain = computed((couponList) => {
		return (couponList) => {
			if (couponList && couponList.length) {
				return couponList.reduce((accumulator, currentValue) => accumulator + currentValue.couponRemain,
					0)
			} else {
				return 0
			}
		}
	})

	// 卡券面额
	const couponPrice = computed(() => {
		return (couponList) => {
			if (couponList && couponList.length) {
				return couponList.reduce((accumulator, currentValue) => accumulator + currentValue.couponPrice,
					0) / 100
			} else {
				return 0
			}
		}
	})
	// 本机机构已分配
	const couponAllocation = computed(() => {
		return (couponList) => {
			if (couponList && couponList.length) {
				return couponList.reduce((accumulator, currentValue) => accumulator + currentValue.numAllocation,
					0)
			} else {
				return 0
			}
		}
	})
	// 本机机构已派发
	const couponConsume = computed(() => {
		return (couponList) => {
			if (couponList && couponList.length) {
				return couponList.reduce((accumulator, currentValue) => accumulator + currentValue.numConsume,
					0)
			} else {
				return 0
			}
		}
	})

	/**
	 *  详情
	 */
	const onDetail = (activityId, remainNum) => {
		getApp().preventActive(() => {
			uni.navigateTo({
				url: '/marketing/coupon/detail?activityId=' + activityId + '&remainNum=' + remainNum
			})
		})

	}

	// 本级机构剩余数量(总数量减去分配数量减去派发数量)
	const couponNum = computed(() => {
		return (couponList) => {
			if (couponList && couponList.length) {
				return couponList.reduce((accumulator, currentValue) => accumulator + currentValue.num -
					currentValue.numAllocation - currentValue.numConsume, 0)
			} else {
				return 0
			}
		}
	})

	/**
	 * 扫码派券
	 * @param {Number} activityId 活动ID
	 * @param {Number} remainingNumber 当前卡券剩余数量
	 */
	async function onScanCode(activityId, remainingNumber, couponList) {
		if (remainingNumber <= 0) {
			$infoBox.toast('本机构卡券可派发数量已用完！')
			return
		}
		uni.scanCode({
			success: async (res) => {
				// 保存扫码结果
				vdata.scanCodeResult = JSON.parse(res.result.trim())
				vdata.scanCodeResult.activityId = activityId
				// 校验回执信息
				const isOpenReceipt = couponList[0].isOpenReceipt
				const receiptContent = couponList[0].receiptContent
				if(isOpenReceipt === 1){	// 开启回执 客户经理填写回执信息后发放卡券
					vdata.scanCodeResult.isOpenReceipt = couponList[0].isOpenReceipt
					vdata.scanCodeResult.receiptType = couponList[0].receiptType
					vdata.scanCodeResult.receiptContent = JSON.parse(couponList[0].receiptContent)
					// 数据重置
					inputData.value = {
						// 普通回执
						name: '',
						phone: '',
						idCard: '',
						address: '',
						detailAddress: '',
						
						// 开卡\手机银行\提额回执
						bankImg: '',	// 银行卡照片
						bankCard: '',	// 银行卡号
						openDate: '',	// 开卡日期
						depositDate: '',	// 提额日期
						deposit: '',	// 额度
						pension: '',	// 养老金账户号
						mchNo: '',	// 商户号
					}
					// 打开回执弹窗
					receiptInformationRef.value.show()
				}else{	// 不需要回执信息 直接派券
					sendCouponToUser(vdata.scanCodeResult)
				}
			},
			fail({
				errMsg
			}) {
				if (errMsg.includes('cancel')) {
					$infoBox.toast('取消扫码')
				} else {
					$infoBox.toast('扫码失败，请稍后再试')
				}
			}
		})
	}
	// 确认提交信息
	const complete = () => {
		// 参数校验通过 派发卡券
		sendCouponToUser(vdata.scanCodeResult)
	}
	/**
	 * 发放卡券
	 */
	async function sendCouponToUser(scanCodeResult){
		uni.showLoading({
			title: '派送中'
		})
		$sendToMchUser({
			...scanCodeResult,
			receiptContent: inputData.value,
		}).then(async ({ code, bizData }) => {
			// 发券失败 用户未授权 引导用户
			if(code === 40005){
				vdata.activityQrcodeImg = 'data:image/png;base64,' + bizData
				qrCodePopup.value.open()
				$infoBox.toast('卡券派送失败')
				return
			}
			// 卡券派送成功 刷新卡券列表
			await refreshActivityList(vdata.queryParams)
			uni.hideLoading()
			$infoBox.toast('卡券派送成功')
		}).finally(() => {
			// 关闭回执弹窗
			receiptInformationRef.value.close()
		})
	}

	/**
	 * 打开搜索弹窗
	 */
	const onOpenSearch = () => {
		searchPopup.value.open();

	}
	/**
	 * 筛选
	 */
	const onQuery = async () => {
		await refreshActivityList(vdata.queryParams)
		onCloseSearch()
	}
	/**
	 * 重置
	 */
	const onReset = () => {
		vdata.queryParams = {
			activityNo: '',
			activityName: '',
			startTime: '',
			endTime: ''
		}
	}

	/**
	 * 关闭搜索弹窗
	 */
	const onCloseSearch = () => {
		searchPopup.value.close();
	}

	/**
	 * 打开日历
	 */
	const onOpenDate = (isStartDate) => {
		vdata.isStartDate = isStartDate
		calendarRef.value.open();
	}

	/**
	 * 日期选择
	 */
	const onConfirmDate = (result) => {
		if (vdata.isStartDate) {
			vdata.queryParams.startTime = result.fulldate
		} else {
			vdata.queryParams.endTime = result.fulldate
		}
	}
</script>

<style lang="less">
	@page-backgroud: #F6F7FC; //页面背景色

	page {
		background: @page-backgroud;
	}
	
	.popup-container{
		padding: 36rpx;
		box-sizing: border-box;
		background: #fff;
		border-radius: 8rpx;
		
		image{
			width: 400rpx;
			height: 400rpx;
		}
		
		view{
			width: 400rpx;
			text-align: center;
		}
	}

	.container {
		min-height: calc(100vh - 60rpx);
		margin: 30rpx 20rpx 30rpx 20rpx;
		overflow: hidden;

		.header-wrap {
			width: 100%;
			position: fixed;
			height: 120rpx;
			top: 0;
			left: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			z-index: 2;
			box-sizing: border-box;
			padding: 0 30rpx;
			background-color: @page-backgroud;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				font-style: normal;
				flex-grow: 1;
			}


			.filter {
				display: flex;
				align-items: center;
				border-radius: 40rpx;
				background-color: white;
				padding: 8rpx 20rpx;
				border: 1rpx solid #C8C8C8;

				text {
					font-size: 26rpx;
					color: black;
					letter-spacing: 1px;
					margin-bottom: 2rpx;
				}
			}
		}

		.content-wrap {
			width: 100%;
			margin-top: 100rpx;
			position: relative;
			z-index: 0;

			.item {
				box-sizing: border-box;
				padding: 30rpx;
				background: #fff;
				border-radius: 20rpx;
				box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);
				display: flex;
				flex-direction: column;
				margin-bottom: 30rpx;
				position: relative;


				.no {
					display: flex;
					font-size: 26rpx;
					color: #999999;

					.noN {
						color: #24C789;
					}

				}

				.line {
					height: 1rpx;
					background-color: #E6E6E6;
					margin: 20rpx 0rpx;
				}

				.title {
					font-weight: bold;
					font-size: 32rpx;
					color: #333333;
					margin: 15rpx 0rpx;
				}

				.number {
					display: flex;
					align-items: center;
					justify-content: space-between;
					color: darkgray;
					font-size: 26rpx;
					margin: 5rpx 0rpx;

					.info {
						margin-top: 30rpx;
						border: 1rpx solid #C8C8C8;
						border-radius: 35rpx;
						background-color: white;
						padding: 15rpx 30rpx;
						color: #333333;
						box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);
					}

					.price {
						font-size: 38rpx;
						color: #FF8833;
						font-weight: bold;
					}

					.qrcode {
						border: 1rpx solid #C8C8C8;
						border-radius: 35rpx;
						background-color: white;
						padding: 15rpx 30rpx;
						color: #333333;
						margin-top: 30rpx;
						box-shadow: 0rpx -10rpx 30rpx -30rpx rgba(0, 0, 0, 0.8);
					}

					.history {
						display: flex;
						align-items: center;
						border-radius: 40rpx;
						background-color: #24C789;
						padding: 8rpx 20rpx;
						margin-top: 30rpx;

						text {
							font-size: 26rpx;
							color: #FFFFFF;
							letter-spacing: 1px;
							margin-bottom: 1rpx;
						}
					}
				}
				
				&>image{
					    position: absolute;
					    width: 200rpx;
					    height: 200rpx;
					    right: 30rpx;
						top: 30rpx;
				}

			}
		}

		.popup-search {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 30rpx;
			font-size: 26rpx;
			background-color: white;
			border-radius: 0 0 20rpx 20rpx;
			letter-spacing: 1px;
			box-sizing: border-box;
			margin-top: 120rpx;

			.item {
				display: flex;
				flex-direction: column;
				font-size: 28rpx;
				margin-bottom: 30rpx;
				width: 100%;

				.input {
					border-radius: 40rpx;
					padding: 18rpx 30rpx;
					background-color: #F6F7FC;
					margin-top: 20rpx;
					font-size: 30rpx;
				}

				.time-wrap {
					display: flex;
					flex-direction: row;
					align-items: center;
					margin-top: 20rpx;

					.time {
						border-radius: 40rpx;
						padding: 18rpx 30rpx;
						background-color: #F6F7FC;
						font-size: 30rpx;
						flex-grow: 1;
						display: flex;
						justify-content: space-between;
					}

					.to {
						margin: 0 20rpx;
					}
				}

			}


			.bottom-wrap {
				display: flex;
				flex-direction: row;
				align-items: center;
				font-size: 30rpx;
				margin-top: 30rpx;
				margin-bottom: 10rpx;
				width: 100%;

				.reset {
					color: black;
					border-radius: 40rpx;
					width: 25%;
					padding: 18rpx 0rpx;
					background-color: #F4F5F5;
					text-align: center;
					margin-right: 30rpx;
				}

				.query {
					color: white;
					border-radius: 40rpx;
					width: 75%;
					padding: 18rpx 0rpx;
					background-color: #24C789;
					margin-top: 30rpx;
					text-align: center;
					margin-bottom: 10rpx;
				}
			}

		}

		.popup-generate-qr {
			display: flex;
			flex-direction: column;
			padding: 40rpx 30rpx;
			font-size: 28rpx;
			background-color: white;
			border-radius: 20rpx 20rpx 0 0;
			letter-spacing: 1px;
			box-sizing: border-box;
			position: relative;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 20rpx;
				text-align: center;
			}

			.close {
				position: fixed;
				right: 0;
				top: 0;
				margin-top: 25rpx;
				margin-right: 25rpx;
			}

			.line {
				height: 1rpx;
				background-color: #E6E6E6;
				margin: 20rpx 0rpx;
			}

			.number {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 30rpx;

				.price {
					font-size: 38rpx;
					color: #FF8833;
					font-weight: bold;
				}
			}

			.radio-label {
				display: flex;
				font-size: 28rpx;
				margin-top: 20rpx;
				align-items: center;
				border-radius: 15rpx;
				background-color: white;
				padding: 20rpx 30rpx;
				border: 1rpx solid #D7D7D7;

				.content {
					display: flex;
					flex-direction: column;

					.number {
						display: flex;
						justify-content: flex-start;
						align-items: center;
						margin: 0;
						padding: 5rpx 0;

						input {
							border-radius: 40rpx;
							padding: 13rpx 40rpx;
							background-color: #F6F7FC;
							font-size: 30rpx;
							width: 80rpx;
							margin: 0 10rpx;
						}
					}
				}
			}

			.bottom-wrap {
				font-size: 30rpx;
				width: 100%;
				color: white;
				border-radius: 40rpx;
				padding: 20rpx 0rpx;
				background-color: #24C789;
				margin-top: 40rpx;
				text-align: center;
				margin-bottom: 10rpx;
			}

		}

		.popup-qr {
			display: flex;
			flex-direction: column;
			padding: 40rpx 30rpx;
			font-size: 28rpx;
			background-color: white;
			border-radius: 20rpx 20rpx 0 0;
			letter-spacing: 1px;
			box-sizing: border-box;
			align-items: center;
			position: relative;

			.title {
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				margin-bottom: 20rpx;
				text-align: center;
			}

			.close {
				position: fixed;
				right: 0;
				top: 0;
				margin-top: 25rpx;
				margin-right: 25rpx;
			}

			.line {
				height: 1rpx;
				background-color: #E6E6E6;
				margin: 20rpx 0rpx;
				width: 100%;
			}

			image {
				width: 70%;
				// border: 10rpx solid #24C78933;
				padding: 10rpx;
				margin: 50rpx 0rpx;
			}

			.bottom-wrap {
				font-size: 30rpx;
				width: 100%;
				color: white;
				border-radius: 40rpx;
				padding: 20rpx 0rpx;
				background-color: #24C789;
				text-align: center;
				margin-bottom: 10rpx;
			}

		}
	}
</style>